package com.iptv.grape;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.iptv.grape.bu.AppConfig;
import com.iptv.grape.bu.GrapeContext;
import com.iptv.grape.bu.IKeyEventPorc;
import com.iptv.grape.bu.factory.BusinessLogicBuilder;
import com.iptv.grape.domain.Channel;
import com.iptv.grape.domain.ChannelBill;
import com.iptv.grape.domain.UserInfo;
import com.iptv.grape.event.DefBridgeHandler;
import com.iptv.grape.event.EventArgs;
import com.iptv.grape.net.NetworkService;
import com.iptv.grape.ui.ChannelBillDlg;
import com.iptv.grape.ui.control.ad.ListViewUI;
import com.iptv.grape.ui.dlg.DlgMgr;
import com.iptv.grape.ui.frgmt.my.impls.SystemInfo;
import com.iptv.grape.ui.frgmt.my.impls.SystemMgr;
import com.iptv.grape.util.AppConstant;
import com.iptv.grape.util.AppLog;
import com.iptv.grape.util.ReadJsonFile;
import com.iptv.grape.util.WebViewUtils;
import com.iptv.grape.video.DefXMediaPlayerEventListener;
import com.iptv.grape.video.XMediaPlayer;
import com.starv.dacqapi.DACQAPI;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

// 主程序MainActivity
public class MainActivity extends BaseActivity {

    private BootBroadcastReceiver mBootBroadcastReceiver = null;


    //String livePalyUlr = "http://111.7.174.11/PLTV/88888888/224/3221225899/index.m3u8?icpid=88888888&servicetype=1";
    private BridgeWebView mWebview;
    private String webViewUrl;
    private SurfaceView surfaceView;
    private XMediaPlayer mediaPlayer = null;
    private ProgressBar progressBar;
    private FrameLayout container;
    private DefBridgeHandler webBidgeHandler;
    private DefXMediaPlayerEventListener playerEventListener;
    private RelativeLayout topLayout;
    private RelativeLayout relSplash;
    private TextView textChannelName;
    private TextView textcurType;


    private RelativeLayout statuLayout;
    private TextView statuName;
    private TextView statuType;
    // 暂停相关的控件
    private RelativeLayout pauseLayout;

    // 按键换台时相关布局控件
    private RelativeLayout changingLayout;
    private TextView changingCenter;
    private TextView changingErrorText;
    // 右下角节目单显示相关控件
    private RelativeLayout showBillLayout;
    private RelativeLayout curBillLayout;
    private RelativeLayout nextBillLayout;
    private TextView curBillTextName;
    private TextView curBillTime;
    private TextView nextBillTextName;
    private TextView nextBillTime;

    @Override
    public XMediaPlayer getXMediaPlayer(){
        return mediaPlayer;
    }

    @Override
    public BridgeWebView getBridgeWebView(){
        return this.mWebview;
    }


    @Override
    public void showTopTitle(String channelName,String typeText){
        topLayout.setVisibility(View.VISIBLE);
        textChannelName.setText(channelName);
        textcurType.setText(typeText);
        statuGone();
    }
    @Override
    public void statuVisible(String name,String type){
        statuLayout.setVisibility(View.VISIBLE);
        statuName.setText(name);
        statuType.setText(type);
        showBillLayout.setVisibility(View.GONE);
    }
    public void statuVisible(){
        String curLiveType =GrapeContext.curGrapeContext().curLiveType();
        if( "Time".equalsIgnoreCase(curLiveType)||"Back".equalsIgnoreCase(curLiveType)) {
            statuLayout.setVisibility(View.VISIBLE);
            showBillLayout.setVisibility(View.GONE);
        }else
            statuLayout.setVisibility(View.GONE);
    }
    @Override
    public void statuGone(){
            statuLayout.setVisibility(View.GONE);
    }

    private Handler hideTopTitleHandler = new Handler();

    private Runnable hideTopTitleRunnable = new Runnable(){

        @Override
        public void run() {
            hideTopTitle();
        }
    };

    // 延时关闭右上角的title(直播频道名称 + 频道号)
    private void delayedHideTopTitle(){
        hideTopTitleHandler.removeCallbacks(hideTopTitleRunnable);
        hideTopTitleHandler.postDelayed(hideTopTitleRunnable, AppConstant.TopTitleDelayedTimeVal);
    }

    @Override
    public void cancelHideTopTitleHandler(){
        hideTopTitleHandler.removeCallbacks(hideTopTitleRunnable);
    }

    @Override
    public void showTopTitleDelayedClose(String channelName,String typeText,ChannelBill nowChannelBill,
                                         ChannelBill nextChannelBill){
        statuGone();
        showTopTitle(channelName,typeText);
        if(nowChannelBill != null){
            showBillLayout.setVisibility(View.VISIBLE);
            curBillLayout.setVisibility(View.VISIBLE);
            curBillTextName.setText(nowChannelBill.getText());
            curBillTime.setText(nowChannelBill.getShowTimeText());
            if(nextChannelBill != null){
                nextBillLayout.setVisibility(View.VISIBLE);
                nextBillTextName.setText(nextChannelBill.getText());
                nextBillTime.setText(nextChannelBill.getShowTimeText());
            }else {
                nextBillLayout.setVisibility(View.GONE);
            }
        }
        else {
            showBillLayout.setVisibility(View.GONE);
            curBillLayout.setVisibility(View.GONE);
            nextBillLayout.setVisibility(View.GONE);
        }
        delayedHideTopTitle();
    }

    public DefXMediaPlayerEventListener getDefXMediaPlayerEventListener(){
        //this.runOnUiThread();
        return this.playerEventListener;
    }

    // 播放完成
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 90:
                    GrapeContext.curGrapeContext().getCurMediaPlayer().seekToVod(GrapeContext.curGrapeContext().getCurPlayVod().getCurLastPlayTime());
                    GrapeContext.curGrapeContext().getCurMediaPlayer().play(GrapeContext.curGrapeContext().getCurActivity(), GrapeContext.curGrapeContext().getCurPlayVod().getPlayUrl());
                    GrapeContext.curGrapeContext().setPlaying(true);
                    GrapeContext.curGrapeContext().setCurPlayType("Vod");
                    break;
            }
        }
    };

    @Override
    public Handler getmHandler(){
        return mHandler;
    }

    @Override
    public void hideTopTitle(){
        topLayout.setVisibility(View.GONE);
        showBillLayout.setVisibility(View.GONE);
        curBillLayout.setVisibility(View.GONE);
        nextBillLayout.setVisibility(View.GONE);
        statuVisible();
    }


    private void showImgToRun(){

        Bitmap bitmap = ReadJsonFile.getRunImgFile();
        if(bitmap != null) {
            relSplash.setBackground(new BitmapDrawable(bitmap));
        }else {
            relSplash.setBackgroundResource(R.mipmap.splash0);
        }
//        timeker();
    }

    @Override
    public void showAdImg(){

        //LinearLayout pauseLayout =findViewById(R.id.pause_layout);
        Bitmap bitmap = ReadJsonFile.getRunImgFile("adimg.jpg");
        if(bitmap != null) {
            pauseLayout.setBackground(new BitmapDrawable(bitmap));
        }else {
            pauseLayout.setBackgroundResource(R.mipmap.splash0);
        }
        pauseLayout.setVisibility(View.VISIBLE);
    }
    @Override
    public void hideAdImg(){
        pauseLayout.setVisibility(View.GONE);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //GrapeContext.curGrapeContext().stopThread();
        GrapeContext.curGrapeContext().init(this);
        webViewUrl = AppConfig.getAppConfig().getWebViewUrl();
        //AppLog.getCurLog().out(AppConfig.getAppConfig().getWebViewUrl());
        //webViewUrl="http://117.158.207.135:8899";
        setContentView(R.layout.activity_main);
        relSplash = findViewById(R.id.rel_splash);
        // 显示开机启动图
        showImgToRun();
        // 访问服务查看是否有新的开机启动图
        NetworkService.getInstance().getAppRunimg();


        mWebview = findViewById(R.id.bdwebview);
        surfaceView = findViewById(R.id.surfaceView);
        progressBar = findViewById(R.id.progressBar);
        container = findViewById(R.id.container);
        playerEventListener = new DefXMediaPlayerEventListener(this);
        mediaPlayer = new XMediaPlayer(surfaceView, progressBar);
        mediaPlayer.setOnPlayerListener(playerEventListener);
        topLayout = findViewById(R.id.topLayout);
        textChannelName = findViewById(R.id.textChannelName);
        textcurType = findViewById(R.id.textcurType);

        statuLayout = findViewById(R.id.statuLayout);
        statuName = findViewById(R.id.statuName);
        statuType = findViewById(R.id.statuType);

        changingLayout = findViewById(R.id.changingLayout);
        changingCenter = findViewById(R.id.changingCenter);
        changingErrorText = findViewById(R.id.changingErrorText);

        showBillLayout = findViewById(R.id.showbillLayout);
        curBillLayout = findViewById(R.id.curbillLayout);
        nextBillLayout = findViewById(R.id.nextbillLayout);

        curBillTextName = findViewById(R.id.curBillTextName);
        curBillTime = findViewById(R.id.curBillTime);
        nextBillTextName = findViewById(R.id.nextBillTextName);
        nextBillTime = findViewById(R.id.nextBillTime);

        //adLayout = findViewById(R.id.ad_layout);
        pauseLayout = findViewById(R.id.pause_layout);
        init();
        // 注册自己到业务处理对象
        GrapeContext.curGrapeContext().registerActivity(this, this.mediaPlayer);

        if (mBootBroadcastReceiver == null) {
            mBootBroadcastReceiver = new BootBroadcastReceiver();
            mBootBroadcastReceiver.registerScreenBroadcastReceiver(this);
        }

        // OperatorID运营商ID（广电:1   电信:2   移动:3   联通:4）
        // TerraceID 平台ID（中兴:1，华为：2，其它：3）
        // ContentID 内容提供商（央视国际:1，杭州华数:2，百事通:3，南方传媒:4，   湖南电视台:5，银河电视:6，国广东方:7，爱上北京:8）
        // Brand 机顶盒品牌
        // Mode 机顶盒型号
        // ApkVersion APK版本
        // ReserveGroup 分组与AAA数据对比获得（此字段为空）
        // CollectType CollectType：采集方式(0:BS组播|1:BS单播:|2:CS组播|3:CS单播)
        // Reserve1 预留1
        // Reserve2 预留2 "712cb7a4-a38f-4d66-bec0-4ee2b997845a"
//        DACQAPI.getInstance().Init("01",                // 业务类型标识
//                UserInfo.curUserInfo().getMac(),            // mac地址,
//                UserInfo.curUserInfo().getUserName(),       // 用户ID
//                "2",
//                //CommUtil.formatDate(new Date(),"yyyyMMddHHmmss"),  // 采集数据时间
//                "3",
//                "3",
//
//                UserInfo.curUserInfo().getBrand(),
//                UserInfo.curUserInfo().getModel(),
//                UserInfo.curUserInfo().getAppKey(),
//                "v1.0",
//                "",
//                "1",
//                this,"","");

        SystemInfo systemInfo = SystemMgr.build();
        DACQAPI.getInstance().Init("01",                // 业务类型标识
                UserInfo.curUserInfo().getMac(),            // mac地址,
                UserInfo.curUserInfo().getUserName(),       // 用户ID
                systemInfo.get0perator(),
                //CommUtil.formatDate(new Date(),"yyyyMMddHHmmss"),  // 采集数据时间
                systemInfo.getCdn(),
                systemInfo.getLicence(),

                UserInfo.curUserInfo().getBrand(),
                UserInfo.curUserInfo().getModel(),
                UserInfo.curUserInfo().getAppKey(),
                systemInfo.getApkVersion(),
                "",
                "1",
                this, "", "");

        //DACQAPI.getInstance().LiveDataAcq()
        //EventBus.getDefault().register(this);
        // 查找焦点
        //new Thread(findFocusView).start();
    }


    private void timeker() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                relSplash.setVisibility(View.GONE);
            }
        }, AppConfig.getAppConfig().getRunImageShowTime() * 1000);
    }

    // 初始化Webview
    private void init() {

        //Glide.with(context).load(listRecommend.get(0).get("poster")).into(imgBottom1);

        mWebview.getSettings().setJavaScriptEnabled(true);
        WebViewUtils.initSetting(mWebview,MainActivity.this,webViewUrl);
        WebViewUtils.initHardwareAccelerate(MainActivity.this);
        WebViewUtils.initWebView(mWebview,MainActivity.this,webViewUrl);
        webBidgeHandler = new DefBridgeHandler(this,this.mediaPlayer);
        WebViewUtils.registerHandler(mWebview,webBidgeHandler);
//        mWebview.addJavascriptInterface(new HyBirdWebCallBack(), "bfWebCallBack");
//        mWebview.addJavascriptInterface(new HyBirdWebCallBack(), "bsVideoCallBack");



        mWebview.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                if (progress == 100) {
                    //加载完成
                    relSplash.setVisibility(View.GONE);
                }
            }
        });
    }


    Runnable findFocusView = new Runnable() {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                View rootview = MainActivity.this.getWindow().getDecorView();
                View aaa = rootview.findFocus();
                AppLog.getCurLog().out( aaa.toString());
            }

        }
    };


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(EventArgs eventArgs){


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case 155:
            // 注册自己到业务处理对象
            GrapeContext.curGrapeContext().closeHandle();
            GrapeContext.curGrapeContext().registerActivity(this, this.mediaPlayer);
            GrapeContext.curGrapeContext().setShowRecommendUI(true);
            GrapeContext.curGrapeContext().setFocus(true);
            GrapeContext.curGrapeContext().setFullScreen(true);

            GrapeContext.curGrapeContext().getChannelDLinkList().getCurChannel().playChannel();
            this.mediaPlayer.fullScreen();
            GrapeContext.curGrapeContext().reSetTimeByAutoClose();
            break;
            case 400:
                if(!NetworkService.getInstance().isNetworkConnected()) {
                    DlgMgr.grapeInitDlg(MainActivity.this, "网络异常请检查网络");
                }
                break;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册事件
        //EventBus.getDefault().unregister(this);
        if (mBootBroadcastReceiver != null) {
            mBootBroadcastReceiver.unRegisterScreenBroadcastReceiver(this);
        }
    }


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if(event.getAction() !=KeyEvent.ACTION_UP) {
            if(GrapeContext.curGrapeContext().isFocus()) {
                IKeyEventPorc proc = BusinessLogicBuilder.createProc(event);
                if (proc == null) {
                    GrapeContext.curGrapeContext().reSetTimeByAutoClose();
                    return super.dispatchKeyEvent(event);
                } else {
                    proc.onKeyDownEvent(this,this.mediaPlayer, GrapeContext.curGrapeContext(),event);
                    return true;
                }
            }
        }
        return super.dispatchKeyEvent(event);
    }

    // 显示换台的界面
    @Override
    public void showChangingLiveUI(){
        hideTopTitle();
        changingLayout.setVisibility(View.VISIBLE);
        statuGone();
    }

    // 设置用户输入的频道号
    @Override
    public void setChangingLiveNo(String num){
        changingCenter.setText(num);
        changingErrorText.setVisibility(View.GONE);
    }

    // 设置用户输入的频道号
    @Override
    public void NoFindNo(){
        //changingCenter.setText(num);
        changingErrorText.setVisibility(View.VISIBLE);
        changingErrorText.setText("暂无该频道");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                hideChangingLiveUI();

            }
        }, 1200);
        statuGone();
    }
    @Override
    public void visibles(){
        pauseLayout.setVisibility(View.GONE);
        showBillLayout.setVisibility(View.GONE);
        topLayout.setVisibility(View.GONE);
        statuLayout.setVisibility(View.GONE);
        changingLayout.setVisibility(View.GONE);
    }

    // 隐藏换台的界面
    @Override
    public void hideChangingLiveUI(){
        changingLayout.setVisibility(View.GONE);
        statuVisible();
    }


    // 弹出节目单的预约
    @Override
    public void showChannelBill(Channel channel, ChannelBill channelBill, boolean isAppointment, ListViewUI listViewUI){
        ChannelBillDlg dlg = new ChannelBillDlg(this,channel,channelBill,isAppointment,listViewUI);
        dlg.show();
    }

    // 弹出预约提醒
    @Override
    public void showAppointmentReminder(Channel channel, ChannelBill channelBill){
        ChannelBillDlg dlg = new ChannelBillDlg(this,channel,channelBill);
        dlg.show();
    }
}
